#!/usr/bin/python2.7

# Copyright (c) 2011 CDN-Tool authors. All rights reserved.
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file.

import threading
import logging

HUB_ADDRESS  = "127.0.0.1:2000"

def thread_print(msg):
  print threading.currentThread().name + ". " + str(msg)


def set_log_handlers(loglevel, logfile, *loggers):
  if logfile:
    loghandler = logging.FileHandler(logfile)
  else:
    loghandler = logging.StreamHandler()
  loglevel = getattr(logging, loglevel, logging.DEBUG)
  formatter = logging.Formatter("%(asctime)s - %(threadName)s "
      "- %(name)s - %(levelname)s - %(message)s")
  loghandler.setLevel(loglevel)
  loghandler.setFormatter(formatter)
  for logger in loggers:
    logging.getLogger(logger).setLevel(loglevel)
    logging.getLogger(logger).addHandler(loghandler)


class LoggingMixIn:

  logger = logging.root

  @classmethod
  def log_init(cls, name=None):
    if name:
      return logging.getLogger(name)
    else:
      return logging.getLogger(cls.__name__)

  def log_request(self, code='-', size='-'):
    self.log_info("Request: %s", self.requestline)

  # *args argument added for backwards compatibility with BaseHTTPServer
  def log_message(self, message, *args):
    self.log_info(message, *args)

  def log_debug(self, message, *args):
    self.logger.debug(message, *args)

  def log_info(self, message, *args):
    self.logger.info(message, *args)

  def log_warning(self, message, *args):
    self.logger.warning(message, *args)
       
  # *args argument added for backwards compatibility with BaseHTTPServer
  def log_error(self, message, *args):
    self.logger.error(message, *args)

  def log_exception(self, message, *args):
    self.logger.exception(message, *args)

